import React, { Component } from 'react'
import { BooksClassify } from './components'
import {
  Icon,
  Pagination,
  Spin,
  Tooltip,
  Input,
  Button,
  message,
  Empty
} from 'antd'

// import { getBooksStore, getBooksCollect } from '../../../requests'
import { getBooksList, bookCollect } from '../../../requests/bookDo'

import $ from 'jquery'
import './index.less'
import { antIcon } from '../../loading'
const Search = Input.Search
export default class BooksShow extends Component {
  constructor() {
    super()
    this.state = {
      //书籍总量
      total: 0,
      //页码
      page: 1,
      //每页书籍列表
      booksListData: [],
      //收藏列表
      collectList:
        JSON.parse(window.sessionStorage.getItem('usermessage')).collect ===
        null
          ? ''
          : JSON.parse(
              window.sessionStorage.getItem('usermessage')
            ).collect.split(','),
      collectTimeDown: true,
      borrowNumDown: true,
      uploadDateDown: true,
      //选择的排序方式
      selectedSort: '',
      isLoading: true
    }
  }
  //页码改变
  onPageChange = currentPage => {
    this.setState({
      page: currentPage
    })
  }
  //请求展示书籍列表
  getShowBooksList = params => {
    getBooksList(params).then(resp => {
      if (resp.data.data.status === 1) {
        const booksListData = resp.data.data.data
        //将每条数据加上key
        booksListData.map(item => {
          return (item['key'] = item.bookId)
        })
        this.setState(
          {
            isLoading: false,
            total: booksListData.length,
            booksListData
            // perpage: resp.data.data.perpage
          },
          () => {
            //每次请求到数据按选中的方式排序
            if (this.state.selectedSort === 'collectNumSort') {
              this.state.collectNumDown
                ? this.state.booksListData.sort(
                    (a, b) => a.collectNum - b.collectNum
                  )
                : this.state.booksListData.sort(
                    (a, b) => b.collectNum - a.collectNum
                  )
            } else if (this.state.selectedSort === 'borrowNumSort') {
              this.state.borrowNumDown
                ? this.state.booksListData.sort(
                    (a, b) => a.borrowNum - b.borrowNum
                  )
                : this.state.booksListData.sort(
                    (a, b) => b.borrowNum - a.borrowNum
                  )
            } else if (this.state.selectedSort === 'uploadDateSort') {
              this.state.uploadDateDown
                ? this.state.booksListData.sort(
                    (a, b) =>
                      new Date(a.uploadDate).getTime() -
                      new Date(b.uploadDate).getTime()
                  )
                : this.state.booksListData.sort(
                    (a, b) =>
                      new Date(b.uploadDate).getTime() -
                      new Date(a.uploadDate).getTime()
                  )
            }
            this.setState({
              booksListData: booksListData
            })
          }
        )
      }
    })
  }
  //排序方法
  booksListSort = () => {
    const _this = this
    $('.bookslist-list span').on('click', function(e) {
      e.stopPropagation()
      if (this.className.includes('collectNumSort')) {
        //收藏量排序
        _this.sortMethod(this, '.collectNumSort')
      } else if (this.className.includes('borrowNumSort')) {
        //借阅量排序
        _this.sortMethod(this, '.borrowNumSort')
      } else if (this.className.includes('uploadDateSort')) {
        //上传时间排序
        _this.sortMethod(this, '.uploadDateSort')
      }
    })
  }
  //排序具体操作
  sortMethod = (__this, className) => {
    const _this = this
    $(__this)
      .addClass('sortactive')
      .siblings()
      .removeClass('sortactive')
    $(__this)
      .addClass('sortactive')
      .siblings()
      .children()
      .addClass('iconactive')
    if (className === '.collectNumSort') {
      _this.state.collectNumDown
        ? $(`${className} i:last-child`)
            .removeClass('iconactive')
            .siblings()
            .addClass('iconactive')
        : $(`${className} i:first-child`)
            .removeClass('iconactive')
            .siblings()
            .addClass('iconactive')
      //收藏量排序
      _this.state.collectNumDown
        ? _this.state.booksListData.sort((a, b) => b.collectNum - a.collectNum)
        : _this.state.booksListData.sort((a, b) => a.collectNum - b.collectNum)
      _this.setState({
        collectNumDown: !_this.state.collectNumDown,
        borrowNumDown: true,
        uploadDateDown: true,
        selectedSort: 'collectNumSort',
        booksListData: _this.state.booksListData
      })
    }
    if (className === '.borrowNumSort') {
      _this.state.borrowNumDown
        ? $(`${className} i:last-child`)
            .removeClass('iconactive')
            .siblings()
            .addClass('iconactive')
        : $(`${className} i:first-child`)
            .removeClass('iconactive')
            .siblings()
            .addClass('iconactive')
      //借阅量排序
      _this.state.borrowNumDown
        ? _this.state.booksListData.sort((a, b) => b.borrowNum - a.borrowNum)
        : _this.state.booksListData.sort((a, b) => a.borrowNum - b.borrowNum)
      _this.setState({
        collectTimeDown: true,
        borrowNumDown: !_this.state.borrowNumDown,
        uploadDateDown: true,
        selectedSort: 'borrowNumSort',
        booksListData: _this.state.booksListData
      })
    }
    if (className === '.uploadDateSort') {
      _this.state.uploadDateDown
        ? $(`${className} i:last-child`)
            .removeClass('iconactive')
            .siblings()
            .addClass('iconactive')
        : $(`${className} i:first-child`)
            .removeClass('iconactive')
            .siblings()
            .addClass('iconactive')
      //上传时间排序
      _this.state.uploadDateDown
        ? _this.state.booksListData.sort(
            (a, b) =>
              new Date(b.uploadDate).getTime() -
              new Date(a.uploadDate).getTime()
          )
        : _this.state.booksListData.sort(
            (a, b) =>
              new Date(a.uploadDate).getTime() -
              new Date(b.uploadDate).getTime()
          )
      _this.setState({
        collectNumDown: true,
        borrowNumDown: true,
        uploadDateDown: !_this.state.uploadDateDown,
        selectedSort: 'uploadDateSort',
        booksListData: _this.state.booksListData
      })
    }
  }
  //根据关键字搜索(在请求下来的数据中筛选)
  searchByKeyWords(keyWords) {
    this.setState({
      isLoading: true
    })
    this.getShowBooksList({ keyWords, status: 'allow' })
  }
  componentDidMount() {
    this.getShowBooksList({ status: 'allow' })
    this.booksListSort()
  }
  //收藏书籍
  collectHandle = bookId => {
    this.setState({
      isLoading: true
    })
    const userId = JSON.parse(window.sessionStorage.getItem('usermessage'))
      .userid
    bookCollect({ userId, bookId }).then(resp => {
      if (resp.data.data.status === 1) {
        console.log(resp.data.data.data)
        this.setState(
          {
            collectList: resp.data.data.data,
            isLoading: false
          },
          () => {
            const usermessage = JSON.parse(
              window.sessionStorage.getItem('usermessage')
            )
            usermessage.collect = this.state.collectList.toString()
            window.sessionStorage.setItem(
              'usermessage',
              JSON.stringify(usermessage)
            )
            message.success('收藏成功')
          }
        )
      }
    })
  }
  //取消收藏
  toBooksCollectPage = () => {
    this.props.history.push('/admin/bookscollect')
  }
  render() {
    return (
      <div className="bookslist">
        <div className="search">
          <Search
            placeholder="请输入关键字"
            onSearch={value => this.searchByKeyWords(value)}
            style={{ width: 200 }}
          />
        </div>
        <BooksClassify getShowBooksList={this.getShowBooksList} />

        <div className="bookslist-list">
          <div className="bookslist-list-nav">
            <div className="bookslist-list-nav-sort">
              <span className="collectNumSort">
                收藏量
                <Icon type="arrow-up" className="iconactive" />
                <Icon type="arrow-down" className="iconactive" />
              </span>
              <span className="borrowNumSort">
                借阅量
                <Icon type="arrow-up" className="iconactive" />
                <Icon type="arrow-down" className="iconactive" />
              </span>
              <span className="uploadDateSort">
                上传时间
                <Icon type="arrow-up" className="iconactive" />
                <Icon type="arrow-down" className="iconactive" />
              </span>
            </div>
            <div className="bookslist-list-nav-show">
              <p>
                共有<span>{this.state.total}</span>本相关作品
                <Tooltip
                  placement="top"
                  title={
                    <div>
                      <p>由于政策和内容原因</p>
                      <p>部分书籍不能显示</p>
                    </div>
                  }
                >
                  <Icon type="question-circle" />
                </Tooltip>
              </p>
            </div>
          </div>
          <Spin indicator={antIcon} spinning={this.state.isLoading}>
            {this.state.booksListData.length === 0 ? (
              <div className="bookslist-list-notbooks">
                <Empty
                  image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original"
                  imageStyle={{
                    height: 60
                  }}
                  description={<span>抱歉!没有找到满足您要求的书籍</span>}
                />
              </div>
            ) : (
              <div className="bookslist-list-content">
                {this.state.booksListData.map((value, index) => {
                  if (
                    (this.state.page - 1) * 8 <= index &&
                    index < this.state.page * 8
                  ) {
                    return (
                      <dl key={value.bookId}>
                        <dt>
                          <img
                            src={require(`../../../assets/booksImages/${
                              value.bookId
                            }.jpg`)}
                            alt=""
                          />
                        </dt>
                        <dd>
                          <p>
                            {value.inventory === 0 ? (
                              <span>
                                {value.bookName}
                                <span className="status-span">(已被借阅)</span>
                              </span>
                            ) : (
                              value.bookName
                            )}
                          </p>
                          <p>
                            <span>{value.author}</span>
                            <span>{value.classify}</span>
                            <span>{value.tags}</span>
                          </p>
                          <p>{value.bookDescribe.substring(0, 70)}...</p>
                          <p>
                            <Icon type="fire" />
                            收藏量:
                            {value.collectNum}
                          </p>
                          <p>
                            <Icon type="folder" />
                            借阅量:
                            {value.borrowNum}
                          </p>
                          <p>
                            上架日期:
                            {value.uploadDate}
                          </p>
                          {this.state.collectList.includes(value.bookId) ? (
                            <Button
                              className="collectBtn collectSuccess"
                              size="small"
                              onClick={this.toBooksCollectPage}
                            >
                              已收藏
                            </Button>
                          ) : (
                            <Button
                              className="collectBtn"
                              size="small"
                              onClick={this.collectHandle.bind(
                                this,
                                value.bookId
                              )}
                            >
                              收藏本书
                            </Button>
                          )}
                        </dd>
                      </dl>
                    )
                  } else {
                    return null
                  }
                })}
                <Pagination
                  pageSize={8}
                  size="small"
                  total={this.state.total}
                  className="pagination"
                  //   onChange={this.onPageChange}
                />
              </div>
            )}
          </Spin>
        </div>
      </div>
    )
  }
}
